package util

import (
	"bytes"
	"crypto/md5"
	"crypto/sha1"
	"encoding/base64"
	"encoding/hex"
	"github.com/fatih/color"
	"strings"
)

func Contain(ary []string, str string) bool {
	for _, v := range ary {
		if v == str {
			return true
		}
	}
	return false
}

func Switch(args ...string) string {
	for _, arg := range args {
		if arg != "" {
			return arg
		}
	}
	return args[0]
}

func SwitchString(args ...*string) *string {
	for _, arg := range args {
		if arg != nil && *arg != "" {
			return arg
		}
	}
	return args[0]
}

func SwitchBool(args ...*bool) *bool {
	for _, arg := range args {
		if arg != nil {
			return arg
		}
	}
	return args[0]
}

func SwitchUint(args ...*uint) *uint {
	for _, arg := range args {
		if arg != nil {
			return arg
		}
	}
	return args[0]
}

func Color(c color.Attribute, args []string) string {
	sb := bytes.NewBuffer(nil)
	for i, arg := range args {
		if i > 0 {
			sb.WriteString(", ")
		}
		sb.WriteString(color.New(c).Sprint(arg))
	}
	return sb.String()
}

func SplitFirst(str, sep string) string {
	return strings.SplitN(str, sep, 2)[0]
}

func RemovePrefix(ary []string, prefix string) []string {
	values := CloneStringList(ary)
	for i, v := range values {
		if strings.HasPrefix(v, prefix) {
			values[i] = strings.TrimPrefix(v, prefix)
		}
	}
	return values
}

func MD5(str string) string {
	dir := md5.Sum([]byte(str))
	return hex.EncodeToString(dir[:])
}

// EncodeBase64Sha1 Returns the base 64 encoded sha1 hash of the given string
func EncodeBase64Sha1(str string) string {
	hash := sha1.Sum([]byte(str))
	return base64.RawURLEncoding.EncodeToString(hash[:])
}

func ContainAny(str string, words ...string) bool {
	for _, p := range words {
		if strings.Contains(strings.ToLower(str), strings.ToLower(p)) {
			return true
		}
	}
	return false
}

func HasAnyPrefix(str string, prefix ...string) bool {
	for _, p := range prefix {
		if strings.HasPrefix(str, p) {
			return true
		}
	}
	return false
}

func SafeSubstring(str string, start, end int) string {
	if start < 0 {
		start = 0
	}
	if end < 0 {
		end = 0
	}
	if start > len(str) {
		start = len(str)
	}
	if end > len(str) {
		end = len(str)
	}
	return str[start:end]
}
